package cn.onlineclass.common;

import cn.onlineclass.entity.OResource;
import cn.onlineclass.vo.AjaxPage;
import cn.onlineclass.vo.AjaxResult;
import cn.onlineclass.util.StringUtil;
import cn.onlineclass.service.ResourseService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class RescourceController {
    public void search(HttpServletResponse response, HttpServletRequest request) throws ServletException, IOException {
        int pageNo = StringUtil.toInt(request.getParameter("pageNo"),1);
        AjaxPage search = ResourseService.INST.search(pageNo, 10);
        String str = JSON.toJSONStringWithDateFormat(search,"yyyy-MM-dd",
                SerializerFeature.WriteMapNullValue, SerializerFeature.WriteNullStringAsEmpty,
                SerializerFeature.WriteNullListAsEmpty,SerializerFeature.WriteNonStringValueAsString);
        response.getWriter().print(str);
    }

    public AjaxResult add(HttpServletResponse response, HttpServletRequest request) throws ServletException, IOException {
        String title = request.getParameter("title");
        String url = request.getParameter("url");
        String icon = request.getParameter("icon");
        boolean inuse = StringUtil.isBlank(request.getParameter("inuse"));
        long majorid = StringUtil.toLong(request.getParameter("majorid"),0);
        OResource o = new OResource(title,url,icon,null,null,inuse,majorid);
        AjaxResult add = ResourseService.INST.add(o);
        return add;
    }

    public void get(HttpServletResponse response, HttpServletRequest request) throws ServletException, IOException {
        long id = StringUtil.toLong(request.getParameter("id"));
        AjaxResult oResource = ResourseService.INST.get(id);
        String s = JSON.toJSONString(oResource);
        response.getWriter().print(s);
    }

    public AjaxResult update(HttpServletResponse response, HttpServletRequest request) throws ServletException, IOException {
        long id = StringUtil.toLong(request.getParameter("id"));
        String title = request.getParameter("title");
        String url = request.getParameter("url");
        String icon = request.getParameter("icon");
        boolean inuse = StringUtil.isBlank(request.getParameter("inuse"));
        long majorid = StringUtil.toLong(request.getParameter("majorid"),0);
        OResource o = new OResource(id,title,url,icon,null,null,inuse,majorid);
        AjaxResult update = ResourseService.INST.update(o);
        return update;
    }

    public AjaxResult del(HttpServletResponse response, HttpServletRequest request) throws ServletException, IOException {
        long id = StringUtil.toLong(request.getParameter("id"));
        AjaxResult del = ResourseService.INST.del(id);
        return del;
    }
}
